package com.yz.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @author yuanzheng
 * @date 2020/7/26-10:58
 */
@Configuration
public class DruidConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }


    @Bean
    public ServletRegistrationBean druidServlet() { //后台监控
        ServletRegistrationBean<StatViewServlet> statViewServletRegistration = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        HashMap<String, String> initParameters = new HashMap<>();
        //druid web登录验证
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "123");

        //允许访问
        initParameters.put("allow", "");

        //禁止访问
        //initParameters.put("guest", "127.0.0.1");

        statViewServletRegistration.setInitParameters(initParameters);
        return statViewServletRegistration;
    }


    @Bean
    public FilterRegistrationBean filterRegistrationBean() { //filter拦截
        FilterRegistrationBean<WebStatFilter> webStatFilterRegistrationBean = new FilterRegistrationBean<>(new WebStatFilter());
        webStatFilterRegistrationBean.addUrlPatterns("/*");
        webStatFilterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*,*.html");
        return webStatFilterRegistrationBean;
    }

}
